In [28]:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
In [29]:
def f(x):
    return (x-1) * (x-2) * (x-3) * (x-5)
In [30]:
def df(x):
    return 4*x*x*x - 33*x*x + 82*x -61
In [31]:
def gd(x0, nu, niter=None, epsilon=None):
    xpred = x0
    xcurrent = xpred - nu*df(xpred)
    xlist = [xcurrent]
    if niter:
        i = 1
        while i <= niter and df(xcurrent) != 0:
            xpred = xcurrent 
            xcurrent = xcurrent - nu*df(xcurrent)
            xlist.append(xcurrent)
            i += 1
    if epsilon:
        while np.abs(xcurrent - xpred) > epsilon and df(xcurrent) != 0:
            xpred = xcurrent 
            xcurrent = xcurrent - nu*df(xcurrent)
            xlist.append(xcurrent)
    return xlist, xcurrent, i
In [33]:
x0 = 5
nu = 0.001
xlist,argmin, nb = gd(x0, nu, 443)
In [34]:
print(argmin)
4.326377282577316
In [8]:
import time
x = np.linspace(0., 6, 100)
plt.plot(x, f(x), 'r--')
for i in range(len(xlist)):
    plt.plot(xlist[i], f(xlist[i]), 'bo')
    #time.sleep(1)
plt.show()
In [9]:
x0 = 5
nu = 0.01
xlist,argmin, nb = gd(x0, nu, 39)
import time
x = np.linspace(0., 6, 100)
plt.plot(x, f(x), 'r--')
for i in range(len(xlist)):
    plt.plot(xlist[i], f(xlist[i]), 'bo')
    #time.sleep(1)
plt.show()
print('xmin: ',argmin, 'nb iterations: ',nb)
xmin:  4.326373035438421 nb iterations:  40
In [ ]: